package com.why.messagedigest;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MainActivity extends AppCompatActivity {

    private String pw = "why123";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


    }

    //md5的点击事件
    public void messageDigest(View view) {
        switch (view.getId()){
            case R.id.md5://32位
                String md5 = messageDigest("MD5", pw);
                Log.d("flag", "--------------------->messageDigest: 运算后的结果:"
                        +md5);
                //运算后的结果:ef623de0437ba8d89b6f3d2fe9b8ae35
                break;
            case R.id.sha1://40位
                String sha1 = messageDigest("SHA-1", pw);
                Log.d("flag", "--------------------->messageDigest: 经过SHA-1运算结果："
                        +sha1);
                //经过SHA-1运算结果：72bf464ea7866010a29882bc5d731f2a2c887df4
                break;

        }
    }

    //运算方法，创建了
    private String messageDigest(String type, String data) {

        //1.创建消息摘要的对象
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(type);

            //2调用对象的方法，进行运算

            //将要运算的数据，加载给MessageDigest
            messageDigest.update(data.getBytes());

            //hash值
            byte[] digest = messageDigest.digest();

            //3.将字节数组转化成该样式：
            //规律：0-9，a-f：16进制表示数据

            //3.1打印运算后的数据
            Log.d("flag", "--------------------->messageDigest: hash值的字节数组长度" +digest.length);

            for (int i = 0; i < digest.length; i++) {
//                Log.d("flag", "--------------------->messageDigest: " +digest[i]);
                //Log.d("flag", "--------------------->messageDigest: 二进制" +Integer.toBinaryString(digest[i]));
            }

            //二进制运算
            StringBuilder builder = new StringBuilder();

            for (int i = 0; i < digest.length; i++) {
                //0xFF = 二进制：1111 1111 ==FF
                //F== 15 二进制 1111=15
                int num = digest[i] & 0xFF;

                if (num<0xF){
                    builder.append(0);
                }

                String result = Integer.toHexString(num);
                builder.append(result);
            }
            //运算后的数据，返回
            return builder.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }


        return null;
    }
}















